const { fileToRequest } = require('../../utils');
const { clientPublicPath } = require('./serverPluginClient');
const path = require('path');
const fs = require('fs').promises;
const hash_sum = require('hash-sum');

function stylePlugin(context) {
  const { app, watcher, root } = context;
  app.use(async (ctx, next) => {
    if (ctx.path.endsWith(".css") && ctx.headers.referer
      && (
        ctx.headers.referer.indexOf('.vue') !== -1
        || ctx.headers.referer.indexOf('.js') !== -1
      )) {
      const filePath = path.join(root, ctx.path);
      const content = await fs.readFile(filePath, 'utf-8');
      const id = JSON.stringify(hash_sum(ctx.path))
      ctx.type = 'js';
      ctx.body = codegenCss(id, content);
      return ctx;
    }
    return next();
  });

  watcher.on('change', (filePath) => {
    if (filePath.endsWith('.css')) {
      const publicPath = fileToRequest(filePath, root)

      watcher.send({
        type: 'style-update',
        path: publicPath,
        changeSrcPath: publicPath,
        timestamp: Date.now()
      })
    }
  })
}

function codegenCss(
  id,
  css
) {
  let code =
    `import { updateStyle } from "${clientPublicPath}"\n` +
    `const css = ${JSON.stringify(css)}\n` +
    `updateStyle(${JSON.stringify(id)}, css)\n`
  code += `export default css`
  return code
}

module.exports = {
  stylePlugin,
  codegenCss
}